/**
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "../../../common/data_utils.h"
#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"
extern void LayernormCustomDo(uint32_t blockDim, void *l2ctrl, void *stream, uint8_t *inputXGm, uint8_t *gammaGm,
    uint8_t *betaGm, uint8_t *outputGm, uint8_t *outputMeanGm, uint8_t *outputVarianceGm, uint8_t *workspace,
    uint8_t *tiling);
#else
#include "tikicpulib.h"
extern "C" __global__ __aicore__ void LayernormCustom(GM_ADDR inputXGm, GM_ADDR gammaGm, GM_ADDR betaGm,
    GM_ADDR outputGm, GM_ADDR outputMeanGm, GM_ADDR outputVarianceGm, GM_ADDR workspace, GM_ADDR tiling);
#endif

constexpr uint32_t BLENGTH = 2;
constexpr uint32_t SLENGTH = 32;
constexpr uint32_t HLENGTH = 16;
constexpr uint32_t BLOCK_DIM = 40;
constexpr uint32_t TILINGDATA_SIZE = 27;
constexpr uint32_t WORKSPACE_SIZE = 1024;

extern uint8_t *GenerateTiling(uint32_t bLength, uint32_t sLength, uint32_t hLength);

static bool CompareResult(const void *outputData, int64_t outSize, std::string goldenName)
{
    void *goldenData;
#ifdef ASCENDC_CPU_DEBUG
    goldenData = (uint8_t *)AscendC::GmAlloc(outSize);
#else
    CHECK_ACL(aclrtMallocHost((void **)(&goldenData), outSize));
#endif
    size_t goldenSize = outSize;
    bool ret = ReadFile("../output/golden_output_" + goldenName + ".bin", goldenSize, goldenData, goldenSize);
    if (ret) {
        printf("ReadFile golden_output_%s.bin success!\n", goldenName.c_str());
    } else {
        printf("test failed!\n");
        return false;
    }
    constexpr float EPS = 1e-5;
    int64_t wrongNum = 0;

    for (int i = 0; i < outSize / sizeof(float); i++) {
        float a = (reinterpret_cast<const float *>(outputData))[i];
        float b = (reinterpret_cast<const float *>(goldenData))[i];
        float ae = std::abs(a - b);
        float re = ae / abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult golden_output_%s.bin failed output is %lf, golden is %lf\n", goldenName.c_str(), a,
                b);
            wrongNum++;
        }
    }
#ifdef ASCENDC_CPU_DEBUG
    AscendC::GmFree((void *)goldenData);
#else
    CHECK_ACL(aclrtFreeHost(goldenData));
#endif
    if (wrongNum != 0) {
        return false;
    } else {
        printf("CompareResult golden_output_%s.bin success!\n", goldenName.c_str());
        return true;
    }
}

int32_t main(int32_t argc, char *argv[])
{
    uint32_t blockDim = BLOCK_DIM;
    size_t workspaceSize = WORKSPACE_SIZE * sizeof(float);
    size_t inputSize_inputX = BLENGTH * SLENGTH * HLENGTH * sizeof(float);
    size_t inputSize_gamma = HLENGTH * sizeof(float);
    size_t inputSize_beta = HLENGTH * sizeof(float);
    size_t outputSize_result = BLENGTH * SLENGTH * HLENGTH * sizeof(float);
    size_t outputSize_mean = BLENGTH * SLENGTH * sizeof(float);
    size_t outputSize_variance = BLENGTH * SLENGTH * sizeof(float);
    size_t tilingFileSize = TILINGDATA_SIZE * sizeof(uint32_t);

#ifdef ASCENDC_CPU_DEBUG
    uint8_t *inputX = (uint8_t *)AscendC::GmAlloc(inputSize_inputX);
    uint8_t *gamma = (uint8_t *)AscendC::GmAlloc(inputSize_gamma);
    uint8_t *beta = (uint8_t *)AscendC::GmAlloc(inputSize_beta);
    uint8_t *result = (uint8_t *)AscendC::GmAlloc(outputSize_result);
    uint8_t *mean = (uint8_t *)AscendC::GmAlloc(outputSize_mean);
    uint8_t *variance = (uint8_t *)AscendC::GmAlloc(outputSize_variance);
    uint8_t *workspace = (uint8_t *)AscendC::GmAlloc(workspaceSize);
    uint8_t *tiling = (uint8_t *)AscendC::GmAlloc(tilingFileSize);

    ReadFile("../input/input_inputX.bin", inputSize_inputX, inputX, inputSize_inputX);
    ReadFile("../input/input_gamma.bin", inputSize_gamma, gamma, inputSize_gamma);
    ReadFile("../input/input_beta.bin", inputSize_beta, beta, inputSize_beta);
    memcpy_s(tiling, tilingFileSize, GenerateTiling(BLENGTH, SLENGTH, HLENGTH), tilingFileSize);

    AscendC::SetKernelMode(KernelMode::AIV_MODE);
    ICPU_RUN_KF(LayernormCustom, blockDim, inputX, gamma, beta, result, mean, variance, workspace,
        tiling); // use this macro for cpu debug
    WriteFile("../output/output_result.bin", result, outputSize_result);
    WriteFile("../output/output_mean.bin", mean, outputSize_mean);
    WriteFile("../output/output_variance.bin", variance, outputSize_variance);
    bool goldenResult = true;
    goldenResult &= CompareResult(result, outputSize_result, "result");
    goldenResult &= CompareResult(mean, outputSize_mean, "mean");
    goldenResult &= CompareResult(variance, outputSize_variance, "variance");
    if (goldenResult) {
        printf("test pass!\n");
    } else {
        printf("test failed!\n");
    }

    AscendC::GmFree((void *)inputX);
    AscendC::GmFree((void *)gamma);
    AscendC::GmFree((void *)beta);
    AscendC::GmFree((void *)result);
    AscendC::GmFree((void *)mean);
    AscendC::GmFree((void *)variance);
    AscendC::GmFree((void *)workspace);
    AscendC::GmFree((void *)tiling);
#else
    CHECK_ACL(aclInit(nullptr));
    aclrtContext context;
    int32_t deviceId = 0;
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    aclrtStream stream = nullptr;
    CHECK_ACL(aclrtCreateStream(&stream));

    uint8_t *inputXHost, *gammaHost, *betaHost, *resultHost, *meanHost, *varianceHost, *workspaceHost, *tilingHost;
    uint8_t *inputXDevice, *gammaDevice, *betaDevice, *resultDevice, *meanDevice, *varianceDevice, *workspaceDevice,
        *tilingDevice;

    CHECK_ACL(aclrtMallocHost((void **)(&inputXHost), inputSize_inputX));
    CHECK_ACL(aclrtMallocHost((void **)(&gammaHost), inputSize_gamma));
    CHECK_ACL(aclrtMallocHost((void **)(&betaHost), inputSize_beta));
    CHECK_ACL(aclrtMallocHost((void **)(&resultHost), outputSize_result));
    CHECK_ACL(aclrtMallocHost((void **)(&meanHost), outputSize_mean));
    CHECK_ACL(aclrtMallocHost((void **)(&varianceHost), outputSize_variance));
    CHECK_ACL(aclrtMallocHost((void **)(&workspaceHost), workspaceSize));
    CHECK_ACL(aclrtMallocHost((void **)(&tilingHost), tilingFileSize));
    CHECK_ACL(aclrtMalloc((void **)&inputXDevice, inputSize_inputX, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&gammaDevice, inputSize_gamma, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&betaDevice, inputSize_beta, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&resultDevice, outputSize_result, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&meanDevice, outputSize_mean, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&varianceDevice, outputSize_variance, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&workspaceDevice, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST));
    CHECK_ACL(aclrtMalloc((void **)&tilingDevice, tilingFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    ReadFile("../input/input_inputX.bin", inputSize_inputX, inputXHost, inputSize_inputX);
    ReadFile("../input/input_gamma.bin", inputSize_gamma, gammaHost, inputSize_gamma);
    ReadFile("../input/input_beta.bin", inputSize_beta, betaHost, inputSize_beta);

    CHECK_ACL(aclrtMemcpy(workspaceDevice, workspaceSize, workspaceHost, workspaceSize, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingFileSize, GenerateTiling(BLENGTH, SLENGTH, HLENGTH), tilingFileSize,
        ACL_MEMCPY_HOST_TO_DEVICE));

    CHECK_ACL(aclrtMemcpy(inputXDevice, inputSize_inputX, inputXHost, inputSize_inputX, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(gammaDevice, inputSize_gamma, gammaHost, inputSize_gamma, ACL_MEMCPY_HOST_TO_DEVICE));
    CHECK_ACL(aclrtMemcpy(betaDevice, inputSize_beta, betaHost, inputSize_beta, ACL_MEMCPY_HOST_TO_DEVICE));

    LayernormCustomDo(blockDim, nullptr, stream, inputXDevice, gammaDevice, betaDevice, resultDevice, meanDevice,
        varianceDevice, workspaceDevice, tilingDevice);
    CHECK_ACL(aclrtSynchronizeStream(stream));
    CHECK_ACL(aclrtMemcpy(resultHost, outputSize_result, resultDevice, outputSize_result, ACL_MEMCPY_DEVICE_TO_HOST));
    CHECK_ACL(aclrtMemcpy(meanHost, outputSize_mean, meanDevice, outputSize_mean, ACL_MEMCPY_DEVICE_TO_HOST));
    CHECK_ACL(
        aclrtMemcpy(varianceHost, outputSize_variance, varianceDevice, outputSize_variance, ACL_MEMCPY_DEVICE_TO_HOST));
    WriteFile("../output/output_result.bin", resultHost, outputSize_result);
    WriteFile("../output/output_mean.bin", meanHost, outputSize_mean);
    WriteFile("../output/output_variance.bin", varianceHost, outputSize_variance);
    bool goldenResult = true;
    goldenResult &= CompareResult(resultHost, outputSize_result, "result");
    goldenResult &= CompareResult(meanHost, outputSize_mean, "mean");
    goldenResult &= CompareResult(varianceHost, outputSize_variance, "variance");
    if (goldenResult) {
        printf("test pass!\n");
    } else {
        printf("test failed!\n");
    }

    CHECK_ACL(aclrtFree(inputXDevice));
    CHECK_ACL(aclrtFree(gammaDevice));
    CHECK_ACL(aclrtFree(betaDevice));
    CHECK_ACL(aclrtFree(resultDevice));
    CHECK_ACL(aclrtFree(meanDevice));
    CHECK_ACL(aclrtFree(varianceDevice));
    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFree(tilingDevice));
    CHECK_ACL(aclrtFreeHost(inputXHost));
    CHECK_ACL(aclrtFreeHost(gammaHost));
    CHECK_ACL(aclrtFreeHost(betaHost));
    CHECK_ACL(aclrtFreeHost(resultHost));
    CHECK_ACL(aclrtFreeHost(meanHost));
    CHECK_ACL(aclrtFreeHost(varianceHost));
    CHECK_ACL(aclrtFreeHost(workspaceHost));
    CHECK_ACL(aclrtFreeHost(tilingHost));

    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
#endif
    return 0;
}
